package org.example.websocket;

import org.example.server.JSONRead;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Date;
import java.util.zip.DataFormatException;

public class SocketConfig extends Thread {
    private Socket socket;

    public SocketConfig(Socket socket) {
        this.socket = socket;
    }

    /**
     * 对截取到的信息进行处理，使用org.example.server文件内数据处理接口进行相应处理
     * @param is 监听接口的数据输出
     * @return 传输结果
     */
    public String handle(InputStream is) throws IOException, DataFormatException {
        byte[] bytes = new byte[1024 * 20 * 8];
        int len = is.read(bytes);
        if(len != -1) {
            StringBuffer request = new StringBuffer();
            request.append(new String(bytes, 0, len, "UTF-8"));
            System.out.println("from client ... \n" + request + "\n当前线程" + Thread.currentThread().getName());
            JSONRead jsonRead = new JSONRead(request, socket);
            Integer res = 0;
            res = jsonRead.operateData();
            if(res == 1) {
                return "ok";
            } else {
                throw new DataFormatException("数据处理异常");
            }
        } else {
            throw new DataFormatException("数据处理异常");
        }
    }

    @Override
    public void run() {
        BufferedWriter writer = null;
        try {
            Date date = new Date();
            System.out.println("客户 - " + socket.getRemoteSocketAddress() + "-> 连接成功 当前时间:" + date.toString());
            InputStream is  = socket.getInputStream();
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            String result = null;
            try {
                result = handle(is);
//                writer.write(result);
//                writer.newLine();
//                writer.flush();
//            } catch (IOException | DataFormatException | IllegalArgumentException e1) {
//                writer.write("error");
//                writer.newLine();
//                writer.flush();
//                System.out.println("发生异常");
//                try {
//                    System.out.println("再次接受！");
//                    result = handle(is);
//                    writer.newLine();
//                    writer.flush();
//                } catch (DataFormatException | SocketTimeoutException e2) {
//                    System.out.println("再次接受，发生异常，关闭链接");
//                }
            } catch (DataFormatException e) {
                e.printStackTrace();
            }
        } catch (SocketTimeoutException socketException) {
            socketException.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
